import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 客户端发送文件给服务端，服务端将文件保存到本地。
 * 并返回 “发送成功”给客户端，并关闭相应的连接。
 */
public class TCPFileTest {
    @Test
    public void client() {
        try (Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 12321);
             FileInputStream fileInputStream = new FileInputStream("src//NetworkTest.java");
             OutputStream outputStream = socket.getOutputStream();
             InputStream inputStream = socket.getInputStream();
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fileInputStream.read(buffer)) != -1) {
//                Thread.sleep(1000);
                outputStream.write(buffer, 0, len);
//                System.out.println(len);
            }
            // 客户端表明不再发送数据
            socket.shutdownOutput();

            // 接收来自于服务端的数据
            while ((len = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            System.out.println(byteArrayOutputStream);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Test
    public void server() {
        try (ServerSocket socket = new ServerSocket(12321);
             FileOutputStream fileOutputStream = new FileOutputStream("accept.txt")) {
            Socket accept = socket.accept();
            InputStream inputStream = accept.getInputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }

            System.out.println("文件接收成功");
            // 服务端发送数据给客户端
            OutputStream outputStream = accept.getOutputStream();
            outputStream.write("发送成功".getBytes());
            outputStream.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
